<template>
  <div>
    <!-- 面包屑区域 -->
    <Breadcrumb></Breadcrumb>
    <el-card>
      <el-row :gutter="20">
        <!-- 搜索框区域 -->
        <el-col :span="9">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
            @clear="getUsersList"
            @change="getUsersList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUsersList"
            ></el-button>
          </el-input>
        </el-col>
        <!-- 添加用户区域 -->
        <el-col :span="4">
          <el-button type="primary" @click="addUsersShow = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table :data="usersList" border stripe style="width: 100%">
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="switchChange(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220">
          <template slot-scope="scope">
            <!-- 编辑区域 -->
            <el-button
              size="mmini"
              type="primary"
              icon="el-icon-edit"
              @click="modifyBackfillShow(scope.row)"
            ></el-button>
            <!-- 删除区域 -->
            <el-button
              size="mmini"
              type="danger"
              icon="el-icon-delete"
              @click="removeUser(scope.row.id)"
            ></el-button>
            <!-- 设置区域 -->
            <el-button
              size="mmini"
              type="warning"
              icon="el-icon-setting"
              @click="setRole(scope.row)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器区域   1.监听每页多少条 2.监听当前页变化 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加用户对话框区域 -->
    <el-dialog title="添加用户" :visible.sync="addUsersShow">
      <el-form :model="addUserList" :rules="addRules" ref="addUserList">
        <el-form-item label="用户名" label-width="80px" prop="username">
          <el-input v-model="addUserList.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" label-width="80px" prop="password">
          <el-input v-model="addUserList.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" label-width="80px">
          <el-input v-model="addUserList.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" label-width="80px">
          <el-input v-model="addUserList.mobile"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addUsersShow = false">取 消</el-button>
        <el-button type="primary" @click="addUsers">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 修改用户对话框区域 -->
    <el-dialog title="修改用户" :visible.sync="modifyShow" width="50%">
      <el-form :model="modifyData" :rules="addRules" ref="modifyData">
        <el-form-item label="用户名" label-width="80px">
          <el-input v-model="modifyData.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" label-width="80px" prop="email">
          <el-input v-model="modifyData.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" label-width="80px" prop="mobile">
          <el-input v-model="modifyData.mobile"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="modifyShow = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 分配角色的对话框 -->
    <el-dialog title="分配角色" :visible.sync="setRoleDialogVisble" @close="setRoleDialogClosed">
      <div>
        <p>当前的用户：{{ userInfo.username }}</p>
        <p>当前的角色：{{ userInfo.role_name }}</p>
        <p>
          分配新角色：
          <el-select v-model="selectedRoleId" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </p>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisble = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import Breadcrumb from "../Breadcrumb";
import usersApi from '@/request/userApi'
export default {
  components: {
    Breadcrumb,
  },
  data() {
    // 自定义验证规则
    var checkAge = (rule, value, callback) => {
      // 验证邮箱的正则
      var reg = /^[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*@[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*\.[a-z]{2,}$/;
      if (!reg.test(value)) {
        callback(new Error("请输入正确的邮箱格式"));
      } else {
        callback();
      }
    };
    var checkAge2 = (rule, value, callback) => {
      // 手机号的正则
      var reg = /^1(3|4|5|6|7|8|9)\d{9}$/;
      if (!reg.test(value)) {
        callback(new Error("请输入正确的电话号码"));
      } else {
        callback();
      }
    };
    return {
      // 用户所有数据
      usersList: [],
      // 用户列表参数
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 2,
      },
      total: null, // 总条数
      addUsersShow: false, // 添加用户对话框开关
      addUserList: {
        // 添加用户
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      // 验证规则
      addRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 5,
            max: 12,
            message: "长度在 5 到 12 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, max: 12, message: "长度在6 到 12 个字符", trigger: "blur" },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkAge, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入电话", trigger: "blur" },
          { validator: checkAge2, trigger: "blur" },
        ],
      },
      // 修改对话框开关
      modifyShow: false,
      // 修改回填
      modifyData: {},
      // 控制分配权限对话框的显示与隐藏
      setRoleDialogVisble: false,
      // 需要被分配角色的用户信息
      userInfo: {},
      // 所有角色的数据列表
      rolesList: [],
      // 已选中的角色ID值
      selectedRoleId: "",
    };
  },
  created() {
    this.getUsersList();
  },
  methods: {
    // 获取所有数据
    async getUsersList() {
      // let { data: res } = await this.$http.get("users", {
      //   params: this.queryInfo,
      // });
      let { data: res } = await usersApi.getUserData({
        params: this.queryInfo,
      });
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.usersList = res.data.users;
      this.total = res.data.total;
      console.log(this.usersList);
    },
    // 监听设置每页显示多少条数据
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.queryInfo.pagesize = val;
      this.getUsersList();
    },
    // 监听设置当前是多少页
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.queryInfo.pagenum = val;
      this.getUsersList();
    },
    // 监听修改用户状态
    async switchChange(row) {
      let { data: res } = await usersApi.userStatePut(row.id,row.mg_state);
      // let { data: res } = await this.$http.put(
      //   `users/${row.id}/state/${row.mg_state}`
      // );
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.$message.success(res.meta.msg);
    },
    // 添加用户
    addUsers() {
      this.$refs.addUserList.validate(async (valid) => {
        if (!valid) return;
        let { data: res } = await usersApi.addUser(this.addUserList);
        console.log(res);
        if (res.meta.status !== 201)
          return this.$http.$message.error(res.meta.msg);
        this.$message.success(res.meta.msg);
        this.addUsersShow = false;
        this.getUsersList();
      });
      this.$refs.addUserList.resetFields();
    },
    // 删除用户
    async removeUser(id) {
      const confirmResult = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      console.log(confirmResult);
      if (confirmResult !== "confirm") return this.$message.info("已取消删除");
      let { data: res } = await usersApi.deleteUser(id);
      if (res.meta.status !== 200) return this.$message.error("删除角色失败！");
      this.$message.success("删除角色成功！");
      this.getUsersList();
    },
    // 修改回填
    modifyBackfillShow(data) {
      this.modifyData = data;
      this.modifyShow = true;
    },
    // 修改对话框中点击确认按钮
    editUser() {
      this.$refs.modifyData.validate(async (valid) => {
        if (!valid) return this.$message.error("请填写完整用户信息");
        const { data: res } = await usersApi.userEdit(this.modifyData.id,
          this.modifyData);
        // const { data: res } = await this.$http.put(
        //   "users/" + this.modifyData.id,
        //   this.modifyData
        // );
        if (res.meta.status !== 200) return this.$message.error("修改用户失败");
        this.$message.success("修改用户成功");
        this.modifyShow = false;
        this.getUsersList();
      });
    },
    // 展示分配角色的对话框
    async setRole(data) {
      this.userInfo = data;
      // 在展示对话框之前，获取所有的角色列表
      let { data: res } = await usersApi.getRolesData();
      if (res.meta.status !== 200)
        return this.$message.error("获取角色列表失败");
      this.rolesList = res.data;
      this.setRoleDialogVisble = true;
    },
    // 点击按钮，分配角色
    async saveRoleInfo() {
      if(!this.selectedRoleId){
        return this.$message.error('请选择要分配的角色！')
      }
      let { data:res} = await usersApi.roleInfo(this.userInfo.id,this.selectedRoleId)
      if(res.meta.status !==200) return this.$message.error('更新角色失败')
      this.$message.success('更新角色成功')
      this.getUsersList();
      this.setRoleDialogVisble = false
    },
    setRoleDialogClosed(){
      this.selectedRoleId = '',
      this.userInfo= {}
    }
  },
};
</script>
<style lang="scss" scoped>
.el-table,
.el-pagination {
  margin-top: 15px;
}
P{
  margin-bottom: 10px;
}
</style>